package qs.openxt.libs.plugins;

import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import qs.openxt.libs.App;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.PictureUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * 文件上传
 * @author 颖杰_2
 *
 */
public class SplashScreenPlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    callbackContext.success((String) msg.obj);
                    break;
                }
                case 2: {
                    Toast.makeText(cordova.getActivity(), (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void sendMessage(int what, String mMessage){
        Message msg = new Message();
        msg.what = what;
        msg.obj = mMessage;
        mHandler.sendMessage(msg);
    }
	
	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doSplashScreenConfigApp".equals(action)) {
            String url = args.optString(0);
            RequestParams params = new RequestParams(url);
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    download(result.toString());
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

            return true;
        }else if ("doCallbackAppVersion".equals(action)) {
            sendMessage(1, ActivityUtil.getVersion(cordova.getActivity()));
            return true;
        }
		return false;
	}

    private void download(String content){
        try{
            if(StringUtil.isNull(content))
                return;
            com.alibaba.fastjson.JSONObject json = JSON.parseObject(content);
            if(json.size() == 0)
                return;
            if(json.containsKey("Message"))
                return;
            final String path = PictureUtil.getSplashScreen().getAbsolutePath();
            com.alibaba.fastjson.JSONArray IMGS = json.getJSONArray("IMGS");
            String CanSkip = json.getString("CanSkip");
            String Mode = json.getString("Mode");
            String ExpiryDate = json.getString("ExpiryDate");
            String IsWait = json.getString("IsWait");
            String ChangeDefault = json.getString("ChangeDefault");

            com.alibaba.fastjson.JSONObject config = null;
            String _config = Utils.getLocalStorage(cordova.getActivity(), App.SPLASHSCREEN);
            if(StringUtil.isNull(_config))
                config = new com.alibaba.fastjson.JSONObject();
            else
                config = JSON.parseObject(_config);

            config.put("CanSkip", CanSkip);
            config.put("Mode", Mode);
            config.put("ExpiryDate", ExpiryDate);
            config.put("IsWait", IsWait);
            config.put("ChangeDefault", ChangeDefault);
            config.put("IMGS", new com.alibaba.fastjson.JSONArray());

            Utils.setLocalStorage(cordova.getActivity(), App.SPLASHSCREEN, config.toString());
            Utils.setLocalStorage(cordova.getActivity(), App.SPLASHSCREEN_ISFIRST, "true");

            for(int i = 0, j = IMGS.size(); i < j; i++){
                String picUrl = IMGS.getString(i);
                final String fileName = picUrl.substring(picUrl.lastIndexOf("/") + 1);
                doDownload(picUrl, path + "/" + fileName, i);
            }
        }catch (Exception e){

        }
    }

    private void doDownload(String url, final String path, final int index){
        RequestParams params = new RequestParams(url);
        //设置断点续传
        params.setAutoResume(true);
        params.setAutoResume(true);
        params.setSaveFilePath(path);
        x.http().get(params, new Callback.CommonCallback<File>() {
            @Override
            public void onSuccess(File result) {
                doSuccess(result.getAbsolutePath(), index);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void doSuccess(String path, int index){
        try {
            com.alibaba.fastjson.JSONObject config = null;
            String _config = Utils.getLocalStorage(cordova.getActivity(), App.SPLASHSCREEN);
            if (StringUtil.isNull(_config))
                config = new com.alibaba.fastjson.JSONObject();
            else
                config = JSON.parseObject(_config);

            com.alibaba.fastjson.JSONArray IMGS = config.getJSONArray("IMGS");
            IMGS.add(index, path);

            Utils.setLocalStorage(cordova.getActivity(), App.SPLASHSCREEN, config.toString());
        }catch (Exception e){

        }
    }
}
